package IO流.IO流操作.节点流.字节数组流;

import java.io.*;
import java.io.ByteArrayInputStream;

/**
 * 1.图片读取到字节数组
 * 2.字节数组写出到文件
 * <p>
 * 实际是字节输入流（IOtest03）与字节数组输出流的（ByteArrayOutputStream）集合
 */
public class PicRead {
    public static void main(String[] args) {
        //图片转成字节数组(存入缓存)
        byte[] data = fileToBYteArray("青蛙.png");
        System.out.println(data.length);
        //从缓存中获取图片
        byteArrayToFile(data, "绿娃.png");
    }

    /**
     * 1.图片读取到字节数组
     * 1).图片到程序 FileInputStream
     * 2).程序写到字节数组 ByteArrayOutStream
     */
    public static byte[] fileToBYteArray(String filePath) {
        //1.创建源
        File src = new File(filePath);
        //2.选择流
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(src);
            outputStream = new ByteArrayOutputStream();
            //3.操作文件
            byte[] pool = new byte[1024 * 10];
            int len = -1;
            while ((len = inputStream.read(pool)) != -1) {
                outputStream.write(pool, 0, len);//写出到字节数组中
            }
            outputStream.flush();
            return outputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //若资源没有被用到，则不用关闭（若不判断会造成空指针异常）
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 2.字节数组写出到图片
     * 1).字节数组到程序  ByteArrayInputStream
     * 2）.程序xie出到图片 outputStream
     */
    public static void byteArrayToFile(byte[] src, String filePath) {
        //1.创建源(目的地)
        File file = new File(filePath);
        //2.选择流
        InputStream is = null;
        OutputStream o = null;
        try {
            //append,是否在文件末尾执行操作。
            o = new FileOutputStream(file);
            is = new ByteArrayInputStream(src);
            //3.操作
            byte[] buf = new byte[5];//缓冲容器
            int len;
            while ((len = is.read(buf)) != -1) {
                o.write(buf, 0, len);
            }
            o.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.释放资源
            try {
                if (o != null) {
                    o.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
}
